<template>
	<div class="dispatch-container">
		<!-- 页面标题 -->
		<div class="page-header">
			<div class="header-left">
				<h2 class="page-title">
					订单调度
					<el-tag v-if="currentOrderNo" class="ml-2"
						>订单号: {{ currentOrderNo }}</el-tag
					>
				</h2>
			</div>
			<div class="header-right">
				<el-button @click="handleBack">返回订单列表</el-button>
			</div>
		</div>

		<el-card class="dispatch-card" shadow="never">
			<!-- 货物信息 -->
			<div class="section-header">
				<span class="section-title">货物信息</span>
				<el-badge value="1" class="item" type="danger" />
			</div>
			<el-table :data="goodsData" border stripe>
				<el-table-column type="index" label="序号" width="60" align="center" />
				<el-table-column prop="name" label="货物名称" min-width="150" />
				<el-table-column
					prop="quantity"
					label="数量"
					width="100"
					align="center"
				/>
				<el-table-column prop="unit" label="单位" width="100" align="center" />
				<el-table-column
					prop="requiredTimes"
					label="需求车次"
					width="100"
					align="center"
				/>
			</el-table>
			<div class="table-footer">
				<div class="total-row">合计</div>
			</div>

			<!-- 配送信息 -->
			<div class="section-header mt-4">
				<span class="section-title">配送信息</span>
			</div>
			<el-form :model="deliveryForm" label-width="100px" class="delivery-form">
				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="起始地">
							<el-input
								v-model="deliveryForm.startLocation"
								placeholder="四川/成都市"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="目的地">
							<el-input
								v-model="deliveryForm.destination"
								placeholder="眉山（眉山）"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="里程">
							<div class="distance-input">
								<el-input v-model="deliveryForm.distance" />
								<span class="unit">KM</span>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="计划装车时间">
							<el-date-picker
								v-model="deliveryForm.planLoadingTime"
								type="datetime"
								placeholder="选择日期时间"
								format="YYYY-M-D HH:mm:ss"
								value-format="YYYY-M-D HH:mm:ss"
								style="width: 100%"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="计划到达时间">
							<el-date-picker
								v-model="deliveryForm.planArrivalTime"
								type="datetime"
								placeholder="选择日期时间"
								format="YYYY-M-D HH:mm:ss"
								value-format="YYYY-M-D HH:mm:ss"
								style="width: 100%"
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<!-- 车辆信息 -->
			<div class="section-header mt-4">
				<span class="section-title">车辆信息</span>
				<div class="dispatch-tip">
					<el-alert
						title="提示：点击计划装车时间、计划到达时间可以更改装卸货时间，在车辆信息显示后可在右侧进行排车。"
						type="warning"
						:closable="false"
						show-icon
					/>
				</div>
				<el-button
					type="primary"
					size="small"
					class="add-car-btn"
					@click="handleAddVehicle"
				>
					<el-icon><Plus /></el-icon>添加
				</el-button>
			</div>

			<el-table :data="vehicleData" border>
				<el-table-column type="index" label="序号" width="60" align="center" />
				<el-table-column prop="dispatchNo" label="调度号" min-width="120" />
				<el-table-column prop="plateNo" label="车牌号" width="100" />
				<el-table-column prop="driverName" label="司机名" width="80" />
				<el-table-column prop="driverPhone" label="联系电话" width="120" />
				<el-table-column prop="company" label="所属运营企业" min-width="150" />
				<el-table-column prop="status" label="车辆调度状态" width="120">
					<template #default="{ row }">
						<el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column
					prop="planLoadingTime"
					label="计划装车时间"
					width="160"
				/>
				<el-table-column
					prop="planArrivalTime"
					label="计划到达时间"
					width="160"
				/>
				<el-table-column label="操作" width="80" fixed="right">
					<template #default="{ $index }">
						<el-button type="danger" link @click="handleRemoveVehicle($index)">
							解除
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<!-- 运费信息 -->
			<div class="section-header mt-4">
				<span class="section-title">运费信息</span>
			</div>
			<el-form :model="feeForm" label-width="100px" class="fee-form">
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="计费方式">
							<el-select
								v-model="feeForm.feeMethod"
								placeholder="请选择"
								style="width: 200px"
							>
								<el-option label="单载+量" value="loadAndQuantity" />
								<el-option label="单价×数量" value="pricePerUnit" />
								<el-option label="一口价" value="fixedPrice" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="运费金额">
							<div class="fee-input">
								<el-input v-model="feeForm.totalFee" />
								<span class="unit">元</span>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>

			<!-- 底部按钮 -->
			<div class="bottom-actions">
				<el-button>取消</el-button>
				<el-button type="primary">保存</el-button>
				<el-button type="success">保存并确认调度</el-button>
			</div>
		</el-card>

		<!-- 添加车辆弹框 -->
		<AddVehicleDialog
			v-model="addVehicleVisible"
			:default-times="deliveryForm"
			@confirm="handleVehicleConfirm"
		/>
	</div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Plus } from '@element-plus/icons-vue';
import AddVehicleDialog from './components/AddVehicleDialog.vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';

// 获取路由实例和参数
const route = useRoute();
const router = useRouter();

// 货物数据
const goodsData = ref([
	{
		name: '机制砂',
		quantity: 200,
		unit: '吨',
		requiredTimes: 8,
	},
]);

// 配送信息
const deliveryForm = reactive({
	startLocation: '四川/成都市',
	destination: '眉山（眉山）',
	distance: 80,
	planLoadingTime: '2025-5-1 7:00:00',
	planArrivalTime: '2025-5-2 20:00:00',
});

// 车辆信息
const vehicleData = ref([
	{
		dispatchNo: 'YD20250422000001',
		plateNo: '川A00515D',
		driverName: '张三',
		driverPhone: '13500000000',
		company: 'XXXX运输有限公司',
		status: '已调',
		planLoadingTime: '2025-5-1 06:00:00',
		planArrivalTime: '2025-5-1 08:00:00',
	},
	{
		dispatchNo: 'YD20250422000002',
		plateNo: '川A00560D',
		driverName: '王五',
		driverPhone: '13500000000',
		company: 'XXXX运输有限公司',
		status: '待确',
		planLoadingTime: '2025-5-1 06:00:00',
		planArrivalTime: '2025-5-1 08:00:00',
	},
	{
		dispatchNo: 'YD20250422000003',
		plateNo: '川A00560D',
		driverName: '王五',
		driverPhone: '13500000000',
		company: 'XXXX运输有限公司',
		status: '待确',
		planLoadingTime: '2025-5-1 15:00:00',
		planArrivalTime: '2025-5-1 12:00:00',
	},
]);

// 运费信息
const feeForm = reactive({
	feeMethod: 'loadAndQuantity',
	totalFee: '',
});

// 添加车辆弹框控制
const addVehicleVisible = ref(false);

// 当前订单编号
const currentOrderNo = ref('');

// 处理添加车辆按钮点击
const handleAddVehicle = () => {
	addVehicleVisible.value = true;
};

// 处理车辆添加成功
const handleVehicleConfirm = (vehicles) => {
	// 这里接收的是一个数组，包含所有选中的车辆
	if (Array.isArray(vehicles)) {
		// 添加多个车辆
		vehicles.forEach((vehicle) => {
			// 检查车辆是否已经存在
			const exists = vehicleData.value.some(
				(v) => v.plateNo === vehicle.plateNo,
			);
			if (!exists) {
				vehicleData.value.push(vehicle);
			}
		});
	} else if (vehicles && vehicles.plateNo) {
		// 添加单个车辆
		const exists = vehicleData.value.some(
			(v) => v.plateNo === vehicles.plateNo,
		);
		if (!exists) {
			vehicleData.value.push(vehicles);
		}
	}
	ElMessage.success('车辆调度成功');
};

// 处理解除车辆
const handleRemoveVehicle = (index) => {
	ElMessageBox.confirm('确认要解除该车辆的调度吗?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(() => {
			vehicleData.value.splice(index, 1);
			ElMessage.success('已解除车辆调度');
		})
		.catch(() => {});
};

// 获取状态类型
const getStatusType = (status) => {
	const statusMap = {
		已调: 'success',
		待确: 'warning',
		已完成: '',
		已取消: 'info',
	};
	return statusMap[status] || 'info';
};

// 返回订单列表
const handleBack = () => {
	router.push('/order'); // 跳转到订单管理页面
};

// 初始化数据
const initData = () => {
	// 获取订单编号
	const orderNo = route.query.orderNo;
	if (orderNo) {
		currentOrderNo.value = orderNo;
		// TODO: 根据订单编号获取详细数据
		console.log('根据订单编号加载调度数据:', orderNo);

		// 这里可以调用API获取订单详情并填充数据
		// 以下是示例，实际应该根据API返回数据填充
		ElMessage.info(`正在为订单 ${orderNo} 进行调度设置`);
	}
};

onMounted(() => {
	initData();
});
</script>

<style lang="scss" scoped>
.dispatch-container {
	padding: 20px;

	.page-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16px;

		.page-title {
			font-size: 18px;
			margin: 0;
			display: flex;
			align-items: center;
		}
	}

	.dispatch-card {
		.section-header {
			display: flex;
			align-items: center;
			margin-bottom: 16px;

			.section-title {
				font-size: 16px;
				font-weight: 500;
				color: #303133;
				position: relative;
				padding-left: 12px;

				&::before {
					content: '';
					position: absolute;
					left: 0;
					top: 50%;
					transform: translateY(-50%);
					width: 3px;
					height: 16px;
					background-color: #409eff;
				}
			}

			.dispatch-tip {
				flex: 1;
				margin: 0 16px;
			}

			.add-car-btn {
				margin-left: auto;
			}
		}

		.table-footer {
			background-color: #f5f7fa;
			padding: 8px 16px;

			.total-row {
				text-align: center;
				font-weight: 500;
			}
		}

		.delivery-form,
		.fee-form {
			padding: 16px 0;
		}

		.distance-input,
		.fee-input {
			display: flex;
			align-items: center;

			.unit {
				margin-left: 8px;
				color: #606266;
			}
		}

		.bottom-actions {
			margin-top: 24px;
			text-align: center;

			.el-button {
				min-width: 100px;
				margin: 0 8px;
			}
		}
	}
}
</style>
